#include "DataBaseConnection.h"




DataBaseConnection* DataBaseConnection::m_instance = NULL;

//====================================================================
//
//
//====================================================================
DataBaseConnection::DataBaseConnection(void)
:	m_connection(NULL)
{
}

//====================================================================
//
//
//====================================================================
DataBaseConnection::~DataBaseConnection(void)
{

}

//====================================================================
//
//
//====================================================================
DataBaseConnection* DataBaseConnection::getInstance()
{
	if(!m_instance)
	{
		m_instance = new DataBaseConnection();
	}

	return m_instance;
}

//====================================================================
//
//
//====================================================================
bool DataBaseConnection::connect()
{
	m_connection = mysql_init(NULL);
	if(m_connection == NULL)
	{
		printf("DataBaseConnection::connect - can't create MySQL-descriptor\n");
		return false;
	}
 
	if(!mysql_real_connect(m_connection, "localhost", "root", "register", "test", 3306, NULL, 0))
	{
		printf("DataBaseConnection::connect - can't connect to MySQL server\n");
		return false;
	}

	/*if(mysql_query(m_connection, "INSERT INTO users (userId, name, health, posX, posY) VALUES('0123456789', 'Yevgeniy', 120, 20, -4)") != 0)
	{
		printf("DataBaseConnection::connect - can't execute INSERT-query\n%s\n", mysql_error(m_connection));
	}*/

	return true;
}

MessageLogIn* DataBaseConnection::getUserData(std::string id)
{
	MYSQL_RES *res;
	MYSQL_ROW row;
	MessageLogIn* msg = NULL;

	printf("Get user data: %s\n", id.c_str());

	if (mysql_query(m_connection,"SELECT * FROM users") != 0)
	{
		printf("DataBaseConnection::getUserData - can't execute query: %s\n", mysql_error(m_connection));
		return NULL;
	}
	if (!(res = mysql_store_result(m_connection))) 
	{
		printf("DataBaseConnection::getUserData - can't get result after last query\n");
		return NULL;
	}
	while((row = mysql_fetch_row(res))) 
	{
		if(std::string(row[0]) == std::string(id))
		{
			msg = new MessageLogIn(id);
			//printf("User data loaded: %s, %s, %s, %s\n", row[1], row[2], row[3], row[4]);
			msg->setData(std::string(row[1]), atoi(row[2]), atoi(row[3]), atoi(row[4]));
			printf("data loaded\n");
			break;
		}
	}

	return msg;
}